#! /usr/bin/env python
#
# Walk through a MEF and print info about it
#
import sys
import ctypes
from fitsio import cfitsio, pyfitsio

htype = {}
htype[cfitsio.IMAGE_HDU]  = 'IMAGE_HDU'
htype[cfitsio.ASCII_TBL]  = 'ASCII_TBL'
htype[cfitsio.BINARY_TBL] = 'BINARY_TBL'

def read_axes_info(ff):

    comment = ctypes.create_string_buffer('\000', cfitsio.FLEN_COMMENT)

    naxis = ctypes.c_int(0)
    status = ctypes.c_int(0)
    cfitsio.fits_read_key(ff.fptr, cfitsio.TINT, 'NAXIS', ctypes.byref(naxis),
                          comment, ctypes.byref(status))

    num_dim = naxis.value

    naxes = []
    for n in range(1, num_dim+1):

        cfitsio.fits_read_key(ff.fptr, cfitsio.TINT, 'NAXIS' + str(n),
                              ctypes.byref(naxis),
                              comment, ctypes.byref(status))

        naxes.append(naxis.value)

    if status.value != 0:
        pyfitsio.handle_error(status)
        
    return naxes

def main(filename = 'atestfil.fit'):
    
    ff = pyfitsio.open(filename)

    numHdus = ff.get_num_hdus()
    print filename, 'has', numHdus, 'HDUS'

    for hdunum in range(1, numHdus+1):

        ff.move_to_hdu(hdunum)
        hdutype = ff.get_hdu_type()

        #ndim = ff.get_img_dim()

        naxes = read_axes_info(ff)
        keysexist, morekeys = ff.get_hdrspace()
        
        print 'HDU no.', hdunum, 'is', htype[hdutype]
        print '  - header has', keysexist, 'keys with space for',
        print morekeys, 'more'
        print '  - data dimensions are', naxes

    ff.close()

if __name__ == '__main__':
    main(filename=sys.argv[1])
